import { defineComponent, ref, resolveDirective, withDirectives } from 'vue'
import type { Form } from '@formily/core'
import { createForm, isField, onFieldInit, onFormInit } from '@formily/core'
import { FormItem, FormLayout, Input } from '@formily/element-plus'
import { useRoute, useRouter } from 'vue-router'
import { ElButton, ElCard, ElCol, ElMessage, ElRow } from 'element-plus'
import { useRequest } from 'ahooks-vue'
import { Step, StepItem } from './components'
import type { Award, AwardReview, Scholarship } from '@/types/scholarship'
import { addReviewers, getApplication, getAwardList, getReviewList, submitApplication } from '@/api/scholarship'
import SchemaForm from '@/components/SchemaForm'
import Upload from '@/formily-components/Upload'
import { auditLevel } from '@/utils/staticDict'
import { useTableSelect } from '@/hooks/usePageTable'

export default defineComponent({
  setup() {
    const route = useRoute()
    const router = useRouter()
    const applicationId = route.query.applicationId as string | undefined

    const level = ['已提交', ...auditLevel.map(i => i.label)]

    const reviewList = ref<AwardReview[]>([])
    const editable = ref(!applicationId)

    const formInit = async (form1: Form<any>) => {
      if (applicationId) {
        const { data } = await getApplication(applicationId)
        form1.setValues(data, 'overwrite')
        if (data.applicationStatus === '已退回') {
          editable.value = true
          form1.editable = true
        }
        else {
          editable.value = false
          form1.editable = false
        }

        reviewList.value.push({
          reviewerId: -1,
          reviewId: -1,
          applicationId: -1,
          reviewerLevel: -1,
          reviewResult: '通过',
          studentId: -1,
          applicationDate: '',
          applicationAwardTypeId: -1,
          applicationAwardType: '',
          applicationStatus: '待审核',
          baseSituation: '',
          studySituation: '',
          awardSituation: '',
          reviewDate: data.applicationDate,
        })
        const { rows } = await getReviewList({ applicationId })
        reviewList.value.push(...rows)
      }
    }

    const form = createForm<Partial<Scholarship>>({
      editable: editable.value,
      initialValues: {
        reviewerLevel: 0,
      },
      effects: () => {
        onFormInit(async (form1) => {
          formInit(form1)
        })
        onFieldInit('layout.reviewerId', async (field) => {
          if (isField(field)) {
            const reviewersList = await addReviewers({ roleKey: 'admin' })
            field.dataSource = reviewersList.map(item => ({
              label: item.userName,
              value: item.userId,
            }))
          }
        })
      },
    })

    const { TableSelect, data: tableData } = useTableSelect<Award, number>(
      {

        getList: getAwardList,
      },
      [
        {
          key: 'title',
          title: '奖学金类型',
        },
        {
          key: 'range',
          title: '申请时间范围',
          render: row => `${row.startTime.replaceAll('-', '.')}-${row.endTime.replaceAll('-', '.')}`,
        },
      ],
      'single',
      (row: Award) => row.applicationAwardTypeId,
    )
    const getAwardType = (applicationAwardTypeId: number) => tableData.value.find(item => item.applicationAwardTypeId === applicationAwardTypeId)?.applicationAwardType

    const schema = {
      type: 'object',
      properties: {
        layout: {
          'type': 'void',
          'x-component': 'FormLayout',
          'x-component-props': {
            labelWidth: 125,
          },
          'properties': {
            applicationAwardTypeId: {
              'type': 'string',
              'x-component': TableSelect,
              'x-decorator': 'FormItem',
              'title': '申请奖学金类型',
              'required': true,
            },
            applicationAwardType: {
              'type': 'string',
              'x-reactions': {
                dependencies: ['.applicationAwardTypeId'],
                fulfill: {
                  state: {
                    value: '{{getAwardType($deps[0])}}',
                  },
                },
              },
            },
            baseSituation: {
              'type': 'string',
              'title': '基本情况',
              'x-component': 'Input.TextArea',
              'x-decorator': 'FormItem',
              'required': true,
            },
            studySituation: {
              'type': 'string',
              'title': '学习情况',
              'x-component': 'Input.TextArea',
              'x-decorator': 'FormItem',
              'required': true,
            },
            awardSituation: {
              'type': 'string',
              'title': '获奖情况',
              'x-component': 'Input.TextArea',
              'x-decorator': 'FormItem',
              'required': true,
            },
            file: {
              'type': 'string',
              'title': '附件',
              'x-component': 'Upload',
              'x-decorator': 'FormItem',
              'x-component-props': {
                fileType: [],
                fileSize: 20,
                limit: 10,
                tips: '提交申请材料（如申请书、成绩单、获奖证书等）',
              },
            },
            reviewerId: {
              'type': 'string',
              'title': '辅导员',
              'x-component-props': {
                clearable: true,
                filterable: true,
              },
              'x-component': 'Select',
              'x-decorator': 'FormItem',
              'required': true,
            },
            reviewer: {
              'type': 'string',
              'x-reactions': {
                dependencies: ['.reviewerId#dataSource', '.reviewerId'],
                fulfill: {
                  state: {
                    value: '{{$deps[0] && $deps[0].find(i => i.value === $deps[1]) && $deps[0].find(i => i.value === $deps[1]).label}}',
                  },
                },
              },
            },
          },
        },
      },
    }

    const getStatus = (status: string) => {
      switch (status) {
        case '不通过':
          return 'fail'
        case '通过':
          return 'success'
        case '待审核':
          return 'waiting'
        default:
          return 'fail'
      }
    }

    const loadingDirective = resolveDirective('loading')

    const { run: doSubmit, loading: submit_loading } = useRequest(submitApplication, { manual: true })

    const submit = () => {
      void form.submit(async (values) => {
        await doSubmit(values)
        ElMessage.success('提交成功')
        if (applicationId)
          formInit(form)
        else
          router.back()
      })
    }

    return () => (
      <div class="p-4 bg-[#F4F7F9] h-full">
        <ElRow class="mb-3">
          <ElCol span={20}>
            <Step>
              {
                reviewList.value.map(
                  row => (
                    <StepItem
                      time={row.reviewDate}
                      title={level[(Number(row.reviewerLevel) || 0) + 1]}
                      content={row.reviewResult === '通过' ? '审核通过' : (row.reviewComment || '')}
                      status={getStatus(row.reviewResult)}
                    />
                  ),
                )
              }
            </Step>
          </ElCol>
          <ElCol span={4}>
            {
              editable.value && withDirectives(
                <ElButton type="primary" onClick={submit}>提交</ElButton>,
                [[loadingDirective, submit_loading.value]],
              )
            }
          </ElCol>
        </ElRow>

        <ElCard>
          <SchemaForm form={form} schema={schema} components={{ Input, Upload, FormItem, FormLayout }} scope={{ getAwardType }} />
        </ElCard>
      </div>
    )
  },
})
